import { ActionContext } from 'vuex';
import cloneDeep from 'lodash/cloneDeep';
import { getFormData } from '@/core/api';
import { FormCard, ControlPproperty } from '@/model/types/formCard';
import { ResponseHandle } from '@/global/util/preUtils';
import { GetAllCard } from '@/global/util/common';
import { saveForm } from '@/views/formDesign/api';

interface State {
  mode: string;
  curCardCode: string;
  form: {
    schemaCode: string;
    schemaName: string;
    formCards: FormCard[];
    formProperty: { [key: string]: any };
    [key: string]: any;
  };
  isLoading: boolean;
}
const getInitData = (): State => {
  return {
    mode: 'design',
    curCardCode: '',
    form: {
      schemaCode: '',
      schemaName: '',
      formCards: [],
      formProperty: {},
    },
    isLoading: false,
  };
};

const state: State = getInitData();
const getters = {
  curCard: (state: State) => {
    return GetAllCard(state.form.formCards).find(
      (it) => it.cardCode === state.curCardCode,
    );
  },
};
const actions = {
  async getFormData(context: ActionContext<State, any>, schemaCode: string) {
    context.commit('SetIsLoading', true);
    const res: any = await getFormData({ schemaCode });
    context.commit('SetIsLoading', false);
    ResponseHandle(res, () => {
      res.data && context.commit('SetForm', res.data);
    });
  },
  async saveForm(context: ActionContext<State, any>) {
    const schemaName = context.state.form.formProperty.schemaName.defaultValue;
    context.commit('SetFormAttr', { schemaName });
    const res: any = await saveForm(context.state.form);
    return res;
  },
};
const mutations = {
  SetIsLoading(state: State, data: boolean) {
    state.isLoading = data;
  },
  SetCurCardCode(state: State, data: string) {
    state.curCardCode = data;
  },
  SetForm(state: State, data: any) {
    state.form = data;
  },
  SetFormAttr(state: State, data: { [key: string]: any }) {
    Object.assign(state.form, data);
  },
  SetFormCards(state: State, data: FormCard[]) {
    state.form.formCards = data;
  },
  AddFormCard(state: State, data: FormCard) {
    state.form.formCards.push(data);
  },
  InsertFormCard(state: State, data: any) {
    state.form.formCards.splice(data.index, 0, data.card);
  },
  RemoveFormCard(state: State, cardCode: string) {
    state.form.formCards = state.form.formCards.filter((it) => {
      if (it.columns) {
        it.columns = it.columns.filter((el) => el.cardCode !== cardCode);
      }
      return it.cardCode !== cardCode;
    });
  },
  AddChildCard(state: State, data: { cards: FormCard[]; cardCode: string }) {
    state.form.formCards = state.form.formCards.map((card) => {
      if (card.cardCode === data.cardCode) {
        card.columns = data.cards;
      }
      return card;
    });
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
